package com.helen.ui.login;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.helen.db.UserHelper;
import com.helen.db.UserTable;
import com.helen.entity.LoginRegisterEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.MainActivity;
import com.helen.ui.userinfo.BindPhoneActivity;
import com.helen.utils.ActivityHelper;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by yang on 2018/4/14.
 * 登录
 * 15156068816
 * 1
 */

public class LoginActivity extends BaseActivity {
    private static final int MSG_AUTH_COMPLETE = 0x001;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case MSG_AUTH_COMPLETE:
                    Platform platform = (Platform)msg.obj;
                    String userId = platform.getDb().getUserId();
                    String nickname = platform.getDb().getUserName();
                    String icon = platform.getDb().getUserIcon();
                    MyLog.e("yang", "userId===" + userId);
                    MyLog.e("yang", "nickname===" +nickname);
                    MyLog.e("yang", "icon===" + icon);
                    shareSdkLoginApi(userId,nickname,icon);
                    break;

            }
            return false;
        }
    });
    @BindView(R.id.et_phone)
    MyEditText etPhone;
    @BindView(R.id.et_password)
    MyEditText etPassword;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_login)
    SuperTextView tvLogin;
    @BindView(R.id.tv_qq_login)
    TextView tvQqLogin;
    @BindView(R.id.tv_wechat_login)
    TextView tvWechatLogin;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.login);
        UserTable userTable = UserHelper.getInstance().getLastLoginUser();
        if (userTable != null) {
            if (userTable.getUserAccount() != null) {
                etPhone.setText(userTable.getUserAccount());
                etPhone.setSelection(userTable.getUserAccount().length());
            }
            if (userTable.getUserPassword() != null) {
                etPassword.setText(userTable.getUserPassword());
                etPassword.setSelection(userTable.getUserPassword().length());
            }
        }


        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.tv_forget_password, R.id.tv_register, R.id.tv_login, R.id.tv_qq_login, R.id.tv_wechat_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_forget_password:
                startActivity(new Intent(LoginActivity.this, FindPasswordActivity.class));
                break;
            case R.id.tv_register:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.tv_login:
                String phone = etPhone.getText().toString().trim();
                String pwd = etPassword.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    MToast.makeTextShort(LoginActivity.this, "手机号不能为空").show();
                    etPhone.requestFocus();
                    return;
                }
                if (!PhoneUtils.isMobileNO(phone)) {
                    MToast.makeTextShort(LoginActivity.this, "手机号格式错误").show();
                    etPhone.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    MToast.makeTextShort(LoginActivity.this, "密码不能为空").show();
                    etPassword.requestFocus();
                    return;
                }
                loginApi("2", phone, pwd);
                break;
            case R.id.tv_qq_login:
                shareSdkApiLogin(QQ.NAME);
                break;
            case R.id.tv_wechat_login:
                shareSdkApiLogin(Wechat.NAME);
                break;
        }
    }

    private void loginApi(String type, final String id, final String psw) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("type", type);
        params.put("id", id);
        params.put("pwd", psw);
        EasyHttp.post(Constants.API_JSONAPI_LOGIN)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "登录失败==" + e.toString());
                        MToast.makeTextShort(LoginActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(LoginActivity.this, result, TAG);
                        if (data != null) {
                            Gson gson = new GsonBuilder().create();
                            LoginRegisterEntity registerEntity = gson.fromJson(data, LoginRegisterEntity.class);
                            MyLog.d("yang", "1id=" + registerEntity.getId());
                            UserHelper.getInstance().saveUserAuth(id, psw, true);
                            UserHelper.getInstance().saveUserInfo(LoginActivity.this, data);
                            MyLog.d("yang", "2id=" + UserHelper.getInstance().getloginEntity(LoginActivity.this).getId());
                            UserHelper.getInstance().setIsLogined(true);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            ActivityHelper.getInstance().finishAllActivity();

                        }
                    }
                });
    }


    private void shareSdkApiLogin(String name) {
        mMProgressDialog.show();
        final Platform platform = ShareSDK.getPlatform(name);
        if (platform.isClientValid()) {
            //客户端可用
        }

        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }

        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
                mMProgressDialog.dismiss();
                MyLog.e("ShareSDK", "onComplete ---->  登录成功" + platform.getDb().exportData());
                Message msg = new Message();
                msg.what = MSG_AUTH_COMPLETE;
                msg.getData().putString("platform",platform.toString());
                msg.obj =  platform;
                handler.sendMessage(msg);

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                mMProgressDialog.dismiss();
                MToast.makeTextLong(LoginActivity.this, throwable.getMessage()).show();
                Log.d("ShareSDK", "onError ---->  登录失败" + throwable.toString());
                Log.d("ShareSDK", "onError ---->  登录失败" + throwable.getStackTrace().toString());
                Log.d("ShareSDK", "onError ---->  登录失败" + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                mMProgressDialog.dismiss();
                MToast.makeTextLong(LoginActivity.this, "登录取消").show();
            }
        });
        platform.SSOSetting(false);
        platform.showUser(null);
    }


    //第三方登录接口
    private void shareSdkLoginApi(final String id,final String name, final String img) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("type", "1");
        params.put("id", id);
        EasyHttp.post(Constants.API_JSONAPI_LOGIN)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "注册失败==" + e.toString());
                        MToast.makeTextShort(LoginActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(LoginActivity.this, result, TAG);
                        if (data != null) {
                            Gson gson = new GsonBuilder().create();
                            LoginRegisterEntity registerEntity = gson.fromJson(data, LoginRegisterEntity.class);
                            MyLog.d("yang", "1id=" + registerEntity.getId());
                            UserHelper.getInstance().saveUserAuth("", "", true);
                            UserHelper.getInstance().saveUserInfo(LoginActivity.this, data);
                            UserHelper.getInstance().setIsLogined(true);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            ActivityHelper.getInstance().finishAllActivity();
                        }else {
                            Intent ti =  new Intent(LoginActivity.this, BindPhoneActivity.class);
                            ti.putExtra("id",id);
                            ti.putExtra("name",name);
                            ti.putExtra("img",img);
                            startActivity(ti);

                        }


                    }
                });
    }

}
